<?php
namespace App\Models\Pay;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use DB;
use App\Models\Area;
use App\Service\Common;

// 付费率统计
class Rate extends  Model{
    var $connection_conf = 'remote_bgsi';

    public function paginate()
    {
    	$perPage = Request::get('per_page', 10);

        $page = Request::get('page', 1);
        $sstart = Request::get('start');
        $end = Request::get('end');
        
        
        $start = ($page-1)*$perPage;
        $area_table = 'area_info';
        $select_db = 'mysql_bgac';

        $rw = \DB::connection($select_db)->table($area_table)->where('deleted_at', 0)->orderBy("id", "desc")->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $data = $rw->get();
        $total = $rw->get()->count();
        $data = $data->toArray();

        // $total = \DB::connection($select_db)->table($area_table)->where('deleted_at', 0)->count();

        // $data = json_decode($data, true);
        
        $finished = [];
        // 最不推荐的写法 临时快速补充功能
        foreach ( $data as &$obj ) {
            
            try {
                $area = \App\Models\Area::getPhysicsArea($obj->areaId);
                if ($finished[$area] ) {
                    continue;
                }
                // ======================
                \App\Models\Area::RemoteBgsiSelectByArea($area);
            
                $obj->new_rate = @$this->getNewRate($sstart, $end, $area);

                $obj->left_rate = @$this->getLeftRate($sstart, $end, $area);
                $obj->left_rate['pay'] -= $obj->new_rate['pay'];

                $obj->total_rate = [
                    'total' => $obj->left_rate['total'] + $obj->new_rate['total'],
                    'pay' => $obj->left_rate['pay'] + $obj->new_rate['pay'],
                ];
                $obj->total_rate['rate'] =  round($obj->total_rate['pay'] / ($obj->total_rate['total'] ?:1)  * 100, 2);
                //DB::connection($this->connection_conf);

                $this->CloseRemoteConn();
                $finished[$area] = 1;           
            } catch (\Exception $e) {
                \Log::error($e->getMessage());
            }
        }
        
        // \Log::debug(__METHOD__, [ $data ]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    // 获取新增付费率
    public function getNewRate($start, $end, $area){
        $start = $this->getDate($start, 'start');
        $end = $this->getDate($end, 'end');

        $rw = DB::connection($this->connection_conf)->table('usr_recharge_record')->join('user_login', 'usr_recharge_record.playerId', 'user_login.player_id')
        ->where('usr_recharge_record.createTime', '>=',  ($start))->where('usr_recharge_record.createTime', '<=',  ($end))
        ->where('user_login.reg_time', '>=', $start)->where('user_login.reg_time', '<=', $end);
        if ($area) {
            $rw->where('usr_recharge_record.area', $area);
        }
        $pay = $rw->groupBy('usr_recharge_record.playerId')->get()->count();

        // mysql remote bgsi
        $rw_u_l = DB::connection($this->connection_conf)->table('user_login')->where('reg_time', '>=', $start)->where('reg_time', '<=', $end)->groupBy('player_id');
        $all = $rw_u_l->get()->count();

        $rate = $all == 0 ? 0 : round($pay / $all * 100, 2) . '%';
        \Log::debug('pay new rate'.$area, [$start, $end, 'pay:'.$pay, 'total:'.$all]);
        return ['rate'=> $rate, 'pay'=>$pay, 'total' => $all];
    }

    // 获取所有用户付费率
    public function getLeftRate($start, $end, $area){
        $start = $this->getDate($start, 'start');
        $end = $this->getDate($end, 'end');

        $rw = DB::connection($this->connection_conf)->table('usr_recharge_record')->where('createTime', '>=',($start))->where('createTime', '<=',  ($end));
        if ($area) {
            $rw->where('area', $area);
        }

        $pay = $rw->groupBy('playerId')->get()->count();

        //  mysql remote bgsi
        $rw_u_l = DB::connection($this->connection_conf)->table('user_login')->where('log_time', '>=', $start)->where('log_time', '<=', $end)
        ->where('reg_time', '<', $start)->groupBy('player_id');
        $all = $rw_u_l->get()->count() ;

        $rate = $all == 0 ? '0' : round($pay / $all * 100, 2) . '%';
        
        \Log::debug('pay all rate'.$area, [$start, $end, 'pay:'.$pay, 'total:'.$all]);
        return ['rate'=> $rate, 'pay'=>$pay, 'total' => $all];

    }

    public function getDate($time, $step = 'start'){

        $last = '';

        'end' == $step && $last = ' 23:59:59';
        'start' == $step && $last = ' 00:00:00';
        if ('start' == $step && !$time) {
            $time = time(); //strtotime('-1 day');
        }
        if ('end' == $step && !$time) {
            $time = time();
        }

        if (is_numeric($time)) {
            $time = date('Y-m-d'.$last, $time);
        }

        return $time;
    }

    public static function sum_result($rt, $one, $nomal_add = null)
    {
        $rt['pay'] = $rt['pay'] + $one['pay'];
        if ($nomal_add) {
            $rt['total'] = $rt['total'] + $one['total'];
        }
        $rt['rate'] =  $rt['total'] ==0 ? 0 : round($rt['pay'] / $rt['total'] * 100, 2) . '%';
        return $rt;
    }

    public function getAllRateData($start, $end)
    {
        // 默认参数值
        // if ( empty($end) ) {
        //     $end = time();
        // }
        
        $area_list = Area::areaAll();
        $result['new'] = ['rate' =>0, 'pay' => 0, 'total' => 0];
        $result['left'] = ['rate' =>0, 'pay' => 0, 'total' => 0];
        
        // 旧逻辑
        // DB::connection($this->connection_conf) 是静态全局的 所以下次 即使改变连接配置，但是不会生效
        // 所以 全服的按每个服  没次循环需要先关闭以前的数据库连接
        $finished = [];
        foreach ($area_list as $obj) {
            $area = \App\Models\Area::getPhysicsArea($obj->areaId);
            
        //     // ======================
            \App\Models\Area::RemoteBgsiSelectByArea($area);

        //     $tmp = $this->getNewRate($start, $end, $obj->areaId);
        //     $result['new'] = self::sum_result($result['new'], $tmp);
            
            $tmp = $this->getLeftRate($start, $end, $obj->areaId);
            $result['left'] = self::sum_result($result['left'], $tmp, !$finished[$area]);
            
            //DB::connection($this->connection_conf);
        //     \Log::debug('order rate '. $obj->areaId, [$tmp]);

            $finished[$area] = 1;
            $this->CloseRemoteConn();  
        }

        //新逻辑
        $start = $this->getDate($start, 'start');
        $end = $this->getDate($end, 'end');
        
        $white_ids= $account_ids= $old_ids = $pay_account=  [];
        $login_white = \DB::connection("mysql_bgac")->table('login_white')->where("state", 1)->get();
        foreach ($login_white as $obj) {
            $white_ids[$obj->account] = 1;
        }

        $sure_pay_list = \DB::connection('mysql_bgac')->table("player_recharge_record")->select("account")->where("createTime", ">=", strtotime($start))->where("createTime", "<=", strtotime($end))->get();
        foreach ($sure_pay_list as $obj) {
            $pay_account[$obj->account] = 1;
        }

        $account_list = \DB::connection('mysql_bgac')->table("account_info")->select("account")->where("createTime", ">=", $start)->where("createTime", "<=", $end)
        ->where("lastPlayerId", ">", 0)->get();
        
        foreach ($account_list as $obj) {
            if ($white_ids[$obj->account]) {
                continue;
            }
            // $account_ids[] = $obj->account;
            $result['new']['total']++;

            if ($pay_account[$obj->account]) {
                $result['new']['pay']++;
            }
        }

        // $old_list = \DB::connection('mysql_bgac')->table("account_info")->select("account")->where("lastLoginTime", ">=", ($start))->where("lastLoginTime", "<=", ($end))->where("createTime", "<", $start)->get();

        // foreach ($old_list as $obj) {
        //     if ($white_ids[$obj->account]) {
        //         continue;
        //     }
        //     $result['left']['total']++;
            
        //     if ($pay_account[$obj->account]) {
        //         $result['left']['pay']++;
        //     }
        // }

    
        // $result['all']['total']= $result['new']['total'] + $result['left']['total'];

        // 老用户组里，付费查的是所有用户所以要修正，减去新用户付费额度
        $result['left']['pay'] = $result['left']['pay'] - $result['new']['pay'];
        $result['left']['rate'] = round($result['left']['pay'] / ($result['left']['total']?:1) * 100, 2) . '%';
        $result['new']['rate'] = round($result['new']['pay'] / ($result['new']['total']?:1) * 100, 2) . '%';
 
        // END 新逻辑

        // 旧逻辑
        $result['all'] = [
            'pay'   =>  $result['left']['pay'] + $result['new']['pay'],
            // left 这里统计的当日老用户的数量
            'total'   =>  $result['left']['total'] + $result['new']['total'],
        ];
        $result['all']['rate'] = round($result['all']['pay'] / ($result['all']['total']?:1) * 100, 2) . '%';
        // \Log::debug('------------', [\Config::get("database.connections.remote_bgsi")]);
        return $result;
    }

    // 关闭远程数据库连接
    public function CloseRemoteConn()
    {
        if ( ! \Config::get("database.connections.remote_bgsi") ) {
            return;
        }
        
        DB::disconnect($this->connection_conf);
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['name']){
            $rw->where("name", 'like', $cond["name"].'%');
        }
        if ($cond["areaId"] or $cond['area']){
            $rw->where("areaId", $cond['areaId'] ?: $cond['area']);
        }

    }
}

